package it.robbocca.backup.smb;

import it.robbocca.backup.smb.R;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleAdapter;

public class SelectFolderActivity extends Activity {
	private String host=null;
	private String folder=null;
	private String mode=null; 
	FTPClient mFtp=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_folder);
        
        // recupero parametri
        Intent intent = getIntent();
        folder = intent.getStringExtra("folder"); //if it's a string you stored.
        
        host = intent.getStringExtra("host"); //if it's a string you stored.
        
        mode = intent.getStringExtra("mode"); //if it's a string you stored.
        
        
        drawGridView();
        
    }  
      
    private void drawGridView() {
        GridView gridview = (GridView) findViewById(R.id.gridView1);
        SimpleAdapter saImageItems=null;
        EditText  editText1 = (EditText) findViewById(R.id.editText1);
        if (mode.trim().equals("FTP")){
        	saImageItems =loadFoldersFtp();
        	editText1.setText("ftp://"+host+"/"+folder);
        }else{
        	saImageItems =loadFolders();
        	
            editText1.setText("smb://"+host+"/"+folder);
        }
//        SimpleAdapter saImageItems =loadFolders();
//        SimpleAdapter saImageItems =loadFoldersFtp();
       
        gridview.setAdapter(saImageItems);  
        
        gridview.setOnItemClickListener(new ItemClickListener());  
	}

    class  ItemClickListener implements OnItemClickListener  
    {  
  public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened   
                                    View arg1,//The view within the AdapterView that was clicked  
                                    int arg2,//The position of the view in the adapter  
                                    long arg3//The row id of the item that was clicked  
                                    ) {  
     
      HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);  
      String selected= ((String)item.get("ItemText")).trim();
    		  
      setTitle(selected);  
      EditText  editText1 = (EditText) findViewById(R.id.editText1);
      
      editText1.setText(editText1.getText().toString()+selected+"/");
      folder+=selected+"/";
      
      drawGridView();
      
      
  }  
        
    }  

    private SimpleAdapter loadFolders() {
    	
    	String smbServer="smb://"+host+"/"+folder;
        
//    	"smb://shared";
    	CharSequence[] listaCartelle=null;
		System.out.println("asas");
		// 1. Instantiate an AlertDialog.Builder with its constructor
//		AlertDialog.Builder builder = new AlertDialog.Builder(win);
//
//		// 2. Chain together various setter methods to set the dialog characteristics
////		builder.setMessage("prova1")
//		builder.setTitle("titolo1");
		
		SimpleAdapter saImageItems=null;
		try {
//			String smbAuth="Workgroup";
//					NtlmPasswordAuthentication psw=new NtlmPasswordAuthentication(smbAuth,"admin","minnie");
//			SmbFile file= new SmbFile(smbServer,psw);
					SmbFile file= new SmbFile(smbServer);
			
			listaCartelle=file.list();
			System.out.println(listaCartelle.length);
			
			
			ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
			
	        for(int i=0;i<listaCartelle.length;i++)  
	        {  
	          HashMap<String, Object> map = new HashMap<String, Object>();  
	          map.put("ItemImage", R.drawable.folder);
	          map.put("ItemText", listaCartelle[i]);
	          lstImageItem.add(map);  
	        }  
	       
	        saImageItems = new SimpleAdapter(this, 
	                                                  lstImageItem,
	                                                  R.layout.item,
	                                                  new String[] {"ItemImage","ItemText"},   
	                                                  new int[] {R.id.ItemImage,R.id.ItemText});  
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return saImageItems;
		
//		CharSequence[] ss={"a","b"};
//		builder.setItems(listaServer, new DialogInterface.OnClickListener() {
//               public void onClick(DialogInterface dialog, int which) {
//               System.out.println("ssaa");
//               SmbFileOutputStream out;
//			try {
//				folder= listaServer[which].toString();
//				out = new SmbFileOutputStream( smbServer+"/"+folder+"/"+"prova.txt", false );
//				out.write("sasso".getBytes());
//				out.close();
//			} catch (SmbException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (MalformedURLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (UnknownHostException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
               
//           }
//		 });
		// 3. Get the AlertDialog from create()
//		AlertDialog dialog = builder.create();
//		dialog.show();
		
	}

    
    private SimpleAdapter loadFoldersFtp() {
    	
        
//    	"smb://shared";
    	FTPFile[] listaCartelle=null;
		System.out.println("asas");
		// 1. Instantiate an AlertDialog.Builder with its constructor
//		AlertDialog.Builder builder = new AlertDialog.Builder(win);
//
//		// 2. Chain together various setter methods to set the dialog characteristics
////		builder.setMessage("prova1")
//		builder.setTitle("titolo1");
		
		SimpleAdapter saImageItems=null;
		try {
//			sa
			if (mFtp==null){
				mFtp=new FTPClient();
				mFtp.connect(host,21); // Using port no=21
				int replyCode = mFtp.getReplyCode();
	            if (!FTPReply.isPositiveCompletion(replyCode)) {
	                System.out.println("Connect failed");
	                return null;
	            }
	            mFtp.enterLocalPassiveMode();
				replyCode = mFtp.getReplyCode();
	            if (!FTPReply.isPositiveCompletion(replyCode)) {
	                System.out.println("Connect failed");
	                return null;
	            }
				mFtp.login("", "");
				replyCode = mFtp.getReplyCode();
	            if (!FTPReply.isPositiveCompletion(replyCode)) {
	                System.out.println("Connect failed");
	                return null;
	            }
			}
			
			
			listaCartelle= mFtp.listDirectories(folder);
			System.out.println(listaCartelle.length);
			
			
			ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
			
	        for(int i=0;i<listaCartelle.length;i++)  
	        {  
	          HashMap<String, Object> map = new HashMap<String, Object>();  
	          map.put("ItemImage", R.drawable.folder);
	          map.put("ItemText", listaCartelle[i].getName());
	          lstImageItem.add(map);  
	        }  
	       
	        saImageItems = new SimpleAdapter(this, 
	                                                  lstImageItem,
	                                                  R.layout.item,
	                                                  new String[] {"ItemImage","ItemText"},   
	                                                  new int[] {R.id.ItemImage,R.id.ItemText});  
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return saImageItems;
		
//		CharSequence[] ss={"a","b"};
//		builder.setItems(listaServer, new DialogInterface.OnClickListener() {
//               public void onClick(DialogInterface dialog, int which) {
//               System.out.println("ssaa");
//               SmbFileOutputStream out;
//			try {
//				folder= listaServer[which].toString();
//				out = new SmbFileOutputStream( smbServer+"/"+folder+"/"+"prova.txt", false );
//				out.write("sasso".getBytes());
//				out.close();
//			} catch (SmbException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (MalformedURLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (UnknownHostException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
               
//           }
//		 });
		// 3. Get the AlertDialog from create()
//		AlertDialog dialog = builder.create();
//		dialog.show();
		
	}
    
    
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_select_folder, menu);
        return true;
    }

    
   

}
